<template>
  <div class="songcatalog_box">
    <v-moreSheet
      :from="from"
      :moreSheetOpened="moreSheetOpened"
      @getSheetOption="getSheetOption"
    />
    <v-songListSheet
      :songListSheetOpend="songListSheetOpend"
      @getSelectSongListId="getSelectSongListId"
      :key="componentKey"
    />
    <f7-popover class="popover-menu" :class="'popover-menu' + songListId">
      <f7-list inset class="backgroundSubColor ">
        <f7-list-button
          class="spanColor"
          title="删除歌单"
          @click.stop="handleDeleteList(songListId)"
          popover-close
        ></f7-list-button>
      </f7-list>
    </f7-popover>
    <div class="buttonBar_box">
      <f7-button @click.stop="goToShare()" v-if="from === 'songCard'">
        <svg-icon icon-class="list_share_white" v-if="getThemeDark" />
        <svg-icon icon-class="list_share" v-else />
      </f7-button>
      <f7-button @click.stop="playAll()">
        <svg-icon icon-class="play_all_white" v-if="getThemeDark" />
        <svg-icon icon-class="play_all" v-else />
      </f7-button>
      <f7-button sortable-toggle=".sortable" v-if="from === 'songCard'">
        <svg-icon iconClass="sort_icon_white" v-if="getThemeDark" />
        <svg-icon iconClass="sort_icon" v-else />
      </f7-button>
      <f7-button @click.stop="goToMulChoice()">
        <svg-icon iconClass="mul_choice_white" v-if="getThemeDark" />
        <svg-icon iconClass="mul_choice" v-else />
      </f7-button>
      <f7-button
        :popover-open="'.popover-menu' + songListId"
        v-if="from === 'songCard'"
      >
        <svg-icon iconClass="icon_more_white" v-if="getThemeDark" />
        <svg-icon iconClass="icon_more" v-else />
      </f7-button>
    </div>

    <f7-list
      sortable
      ref="logList"
      @sortable:sort="onSort"
      class="infinite-scroll-content backgroundSubColor"
    >
      <ul ref="vUl" v-if="vlData.items.length" class="backgroundSubColor">
        <f7-list-item
          v-for="(item, index) in vlData.items"
          :key="index"
          @click.stop="playSelected(item, index)"
        >
          <div slot="title" class="itemTitle">
            <div class="index_box titleColor">{{ index + 1 }}.</div>
            <div class="title_box titleColor">
              {{ item.name }}
            </div>
          </div>
          <div slot="footer" class="itemFooter">
            <svg-icon
              iconClass="no_favorite_white"
              v-if="!item.isFavorite && getThemeDark"
            />
            <svg-icon
              iconClass="is_favorite"
              v-else-if="item.isFavorite && getThemeDark"
            />
            <svg-icon
              iconClass="no_favorite"
              v-else-if="!item.isFavorite && !getThemeDark"
            />
            <svg-icon
              iconClass="is_favorite"
              v-else-if="item.isFavorite && !getThemeDark"
            />
            <div class="titleSubColor">{{ item.singer }}</div>
          </div>
          <div slot="after" class="itemAfter">
            <f7-button
              style="display:flex;align-items:center"
              @click.stop="handleSelectMore(item, index)"
            >
              <svg-icon
                iconClass="icon_more_white"
                v-if="getThemeDark"
                style="transform:rotate(90deg)"
              />
              <svg-icon
                iconClass="icon_more"
                v-else
                style="transform:rotate(90deg)"
              />
            </f7-button>
          </div>
        </f7-list-item>
      </ul>
      <!-- <div class="preloader infinite-scroll-preloader"></div> -->
      <div
        v-if="!vlData.items.length"
        style="position:absolute;top:0;left:0;width:100%;text-align:center;margin:0.5rem 0"
      >
        <span style="font-size:16px;" class="spanColor">暂无歌曲</span>
      </div>
    </f7-list>
  </div>
</template>
<script>
import MoreSheet from '@/components/moresheet.vue'
import SongListSheet from '@/components/songlistsheet.vue'
import { mapGetters, mapActions, mapMutations } from 'vuex'
import {
  getSongs,
  addSongToList,
  delSongList,
  delSongFromList,
  getMyFavorites,
  sortSongsInList,
} from '@/api/index.js'
import { deleteFromSongsLib } from '@/api/upload.js'

export default {
  components: {
    'v-moreSheet': MoreSheet,
    'v-songListSheet': SongListSheet,
  },
  computed: {
    ...mapGetters({
      getUserInfo: 'getUserInfo',
      getList: 'getList',
      getThemeDark: 'getThemeDark',
      getPlayState: 'getPlayState',
      nowSong: 'nowSong',
    }),
    infiniteId() {
      return '#' + this.from + this.tRef
    },
  },
  props: {
    songListId: {
      type: Number,
      default: -1,
    },
    listData:{
      type:Object,
      default:()=>{
        return {

        }
      }
    },
    from: {
      type: String,
      default: 'whole',
    },
    tRef: {
      type: String,
      default: 't',
    },
    searchType: {
      type: String,
      default: '',
    },
    searchContent: {
      type: String,
      default: null,
    },
    listHeight: {
      type: String,
      default: '60vh',
    },
   
  },
  watch: {
    songListId: {
      handler(value) {
        if (value != -1) {
          this.queryData.songList = value
        }
      },
      deep: true,
      immediate: true,
    },
    //虚拟列表高度刷新
    vlData: {
      handler(newVal) {
        // console.log('vlData is watched!', newVal)
        this.$nextTick(() => {
          //此处使用这个可以等节点渲染后再获取节点
          this.$refs.vUl.style.height = `${60 * newVal.items.length}px`
        })
      },
      deep: true,
    },
    currentIndex: {
      handler(newVal) {
        console.log('currentIndex is watched!', newVal)
      },
      deep: true,
      immediate: true,
    },
    searchType: {
      handler(newVal) {
        this.queryData.type = newVal
      },
      deep: true,
      immediate: true,
    },
    searchContent: {
      handler(newVal) {
        this.queryData.content = newVal
      },
      deep: true,
      immediate: true,
    },
  },
  data() {
    const items = []
    return {
      items,
      vlData: {
        items: [],
      },
      allowInfinite: true, //是否还需要无限滚动
      maxItems: 40, //列表最大长度
      queryData: {
        // content:'',
        // type:'name(歌曲名)|singer',
        from: 0,
        size: 40,
        // songList:'歌单名',
      },
      delQueryData: {
        id: '',
      },
      currentIndex: -1,
      componentKey: 0, //强制刷新组件
      moreSheetOpened: false, //更多浮层是否显示
      songListSheetOpend: false, //选择歌单列表浮层是否显示
    }
  },
  methods: {
    ...mapActions({
      sendMusic: 'sendMusic',
      selectMusic: 'selectMusic',
      delMusic: 'delMusic',
      play: 'play',
      playMust: 'playMust',
      sendandchangeMusic: 'sendandchangeMusic',
    }),
    ...mapMutations({
      PLAY: 'PLAY',
    }),

    //删除歌单
    handleDeleteList(songListId) {
      let self = this
      //增加删除歌单确认dialog
      this.$f7ready((f7) => {
        f7.dialog.confirm('确定删除歌单吗?', function() {
          console.log('delete this song list')
          self.delQueryData.id = self.songListId
          delSongList(self.delQueryData)
            .then((res) => {
              if (res.code === 200) {
                var toastTop = f7.toast.create({
                  text: '删除成功',
                  position: 'top',
                  closeTimeout: 1500,
                })
                toastTop.open()
                f7.views.main.router.back()
              } else {
                console.log(res.code)
              }
            })
            .catch((err) => {})
        })
      })
    },
    //播放选中
    playSelected(item, index) {
      if (
        this.getPlayState &&
        this.nowSong.songId === this.vlData.items[index].songId
      ) {
      } else {
        this.sendandchangeMusic(this.vlData.items[index])
        this.playMust()
      }

      this.$f7ready((f7) => {
        f7.views.main.router.navigate('/playerInfo/',{
          props:{
            from:this.from,
          }
        })
      })
    },
    //分享歌单
    goToShare(){
      let self = this;
      this.$f7router.navigate('/toShare/', {
        props: {
          shareType: 'songList',
          share: [self.listData],
        },
      })
    },
    //播放全部
    playAll() {
      let self = this
      this.$f7ready((f7) => {
        f7.dialog.confirm('确定播放此歌单全部歌曲吗?', function() {
          //清空播放列表
          while (self.getList.length){
            self.delMusic(0)
          }
    
          //将歌单中的歌放入播放列表
          self.vlData.items.forEach((item) => {
            self.sendMusic(item)
          })
          self.selectMusic(0)
          self.playMust()
          var toastTop = f7.toast.create({
            text: '开始播放此歌单',
            position: 'top',
            closeTimeout: 1500,
          })
          toastTop.open()
        })
      })
    },
    getData() {
      let self = this
      //获取歌曲
      //普通歌单
      if (this.from != 'favorite') {
        getSongs(this.queryData)
          .then((res) => {
            if (res.code === 200) {
              if (Array.isArray(res.data.result) && res.data.result.length) {
                res.data.result.forEach((item) => {
                  this.vlData.items.push({
                    ...item,
                    index: this.vlData.items.length,
                  })
                })
              }
              this.$f7ready((f7) => {
                //如果初始数据已经是全部数据，则去掉无限滚动
                if (self.vlData.items.length >= res.data.total) {
                  // Nothing more to load, detach infinite scroll events to prevent unnecessary loadings
                  f7.infiniteScroll.destroy(
                    `${self.infiniteId} .infinite-scroll-content`
                  )
                  // Remove preloader
                  self
                    .$$(`${self.infiniteId} .infinite-scroll-preloader`)
                    .remove()
                }
                else {
                  self.queryData.from=self.vlData.items.length;
                  self.getData();
                }
              })
            }
          })
          .catch((err) => {
            console.log(err)
          })
      }
      //我喜欢的
      else {
        this.queryData.userId = this.getUserInfo.userid
        getMyFavorites(this.queryData)
          .then((res) => {
            if (res.code === 200) {
              if (Array.isArray(res.data.result) && res.data.result.length) {
                res.data.result.forEach((item) => {
                  self.vlData.items.push(item)
                })
              }
              this.$f7ready((f7) => {
                //如果初始数据已是全部数据，则去掉无限滚动
                if (self.vlData.items.length >= res.data.total) {
                  // Nothing more to load, detach infinite scroll events to prevent unnecessary loadings
                  f7.infiniteScroll.destroy(
                    `${self.infiniteId} .infinite-scroll-content`
                  )
                  // Remove preloader
                  self
                    .$$(`${self.infiniteId} .infinite-scroll-preloader`)
                    .remove()
                }
                else {
                  self.queryData.from=self.vlData.items.length;
                  self.getData();
                }
              })
            }
          })
          .catch((err) => {
            console.log(err)
          })
      }
    },
    onSort(data) {
      // Sort data
      console.log(data)
      let qData = {
        userId: this.getUserInfo.userid,
        songListId: this.songListId,
        from: data.from,
        to: data.to,
      }
      sortSongsInList(qData)
        .then((res) => {

          let lis = this.$refs.vUl.children
          if (data.from < data.to) {
            for (let i = data.from; i <= data.to; i++) {
              lis[i].querySelectorAll(
                "div[class='index_box titleColor']"
              )[0].innerHTML = `${i + 1}.`
            }
          } else {
            for (let i = data.to; i <= data.from; i++) {
              lis[i].querySelectorAll(
                "div[class='index_box titleColor']"
              )[0].innerHTML = `${i + 1}.`
            }
          }
        })
        .catch((err) => {})
    },
    //进入多选页面
    goToMulChoice() {
      let self = this
      this.$f7router.navigate('/multipleChoice/', {
        props: {
          propData: self.vlData.items,
          from: self.from,
          songListId: self.songListId,
          tRef: self.tRef,
        },
      })
    },

    renderExternal(vl, vlData) {
      // console.log(vlData)
      // this.vlData = vlData
    },
    //处理对歌曲item的更多操作，收藏，添加到歌单，
    getSheetOption(option) {
      this.moreSheetOpened = false
      if (option === 1) {
        console.log('添加到播放列表')
        this.$store.dispatch('sendMusic', this.vlData.items[this.currentIndex])
      } else if (option === 2) {
        console.log('添加到歌单')
        this.componentKey++
        this.songListSheetOpend = true
      } else if (option === 3) {
        console.log('从歌单删除')
        console.log(this.currentIndex, '删除前的currentIndex')
        let qData = {
          songId: parseInt(this.vlData.items[this.currentIndex].songId),
          userId: this.getUserInfo.userid,
          songListId: this.songListId,
        }
        delSongFromList(qData)
          .then((res) => {
            if (res.code === 200) {
              this.vlData.items.splice(this.currentIndex, 1)
              this.$f7ready((f7) => {
                let toastTop = f7.toast.create({
                  text: '删除成功',
                  position: 'top',
                  closeTimeout: 1500,
                })
                toastTop.open()
              })
            } else {
              console.log(res.code)
            }
          })
          .catch((err) => {
            console.log(err)
          })
      } else if (option === 4) {
        let self = this
        this.$f7ready(function(f7) {
          f7.dialog.confirm('确定从曲库中删除此歌曲吗?', function() {
            deleteFromSongsLib({
              id: self.vlData.items[self.currentIndex].songId,
            })
              .then((res) => {
                if (res.code === 200) {
                  var toastTop = f7.toast.create({
                    text: '删除成功',
                    position: 'top',
                    closeTimeout: 1500,
                  })
                  toastTop.open()
                  self.vlData.items.splice(self.currentIndex, 1)
                } else {
                  var toastTop = f7.toast.create({
                    text: '删除失败',
                    position: 'top',
                    closeTimeout: 1500,
                  })
                  toastTop.open()
                }
              })
              .catch((err) => {})
          })
        })
      }
    },
    //处理点击更多时是哪个
    handleSelectMore(item, index) {
      this.currentIndex = index
      console.log(this.currentIndex, '--------currentIndex----------')
      this.option = 0
      this.moreSheetOpened = true
    },
    //处理添加到歌单操作
    getSelectSongListId(songListId) {
      this.songListSheetOpend = false
      if (!songListId) {
        return
      }
      let qData = {
        songId: parseInt(this.vlData.items[this.currentIndex].songId),
        userId: this.getUserInfo.userid,
        songListId: songListId,
      }
      let self = this
      addSongToList(qData)
        .then((res) => {
          if (res.code === 200) {
            this.$f7ready((f7) => {
              var toastTop = f7.toast.create({
                text: '添加成功',
                position: 'top',
                closeTimeout: 1500,
              })
              toastTop.open()
            })
          } else if (res.code === 500) {
            this.$f7ready((f7) => {
              var toastTop = f7.toast.create({
                text: res.message,
                position: 'top',
                closeTimeout: 1500,
              })
              toastTop.open()
            })
          }
        })
        .catch((err) => {})
    },
  },
  updated() {
    // console.log('update-------------');
    // this.getData();
  },
  mounted() {
    console.log('进入了songcatalog的mounted', this.from+this.tRef)
    //改变list height
    this.$refs.logList.$el.style.height = this.listHeight
    this.getData()
    // this.vlData.items = this.items
    let self = this
    //监听从多选页面删除歌曲回来后，同步更新歌词列表
    self.$bus
      .$off('delInMultiplechoice' + self.from+self.tRef)
      .$on('delInMultiplechoice' + self.from+self.tRef, (delList) => {
        console.log('进入了delInMultiplechoice的监听回调中')

        let Len = self.vlData.items.length
        for (let i = Len - 1; i >= 0; i--) {
          if (delList.indexOf(self.vlData.items[i].songId) != -1) {
            self.vlData.items.splice(i, 1)
          }
        }
      })
    this.$f7ready((f7) => {
      //无限滚动的监听
      self
        .$$(`${self.infiniteId} .infinite-scroll-content`)
        .on('infinite', function() {
          console.log('infinite')
          if (!self.allowInfinite) return
          //Set loading flag
          self.allowInfinite = false

          //获取歌曲
          self.queryData.from = self.vlData.items.length
          //普通歌单
          if (this.from != 'favorite') {
            getSongs(self.queryData)
              .then((res) => {
                self.allowInfinite = true
                if (res.code === 200) {
                  if (
                    !Array.isArray(res.data.result) ||
                    !res.data.result.length ||
                    res.data.result.length < self.queryData.size
                  ) {
                    // Nothing more to load, detach infinite scroll events to prevent unnecessary loadings
                    f7.infiniteScroll.destroy(
                      `${self.infiniteId} .infinite-scroll-content`
                    )
                    // Remove preloader
                    self
                      .$$(`${self.infiniteId} .infinite-scroll-preloader`)
                      .remove()
                  }
                  Array.isArray(res.data.result) &&
                    res.data.result.length &&
                    res.data.result.forEach((item) => {
                      self.vlData.items.push({
                        ...item,
                        index: self.vlData.items.length,
                      })
                    })
                }
              })
              .catch((err) => {
                console.log(err)
                self.allowInfinite = true
              })
          }
          //我喜欢的
          else {
            getMyFavorites(self.queryData)
              .then((res) => {
                self.allowInfinite = true
                if (res.code === 200) {
                  if (
                    !Array.isArray(res.data.result) ||
                    !res.data.result.length ||
                    res.data.result.length < self.queryData.size
                  ) {
                    // Nothing more to load, detach infinite scroll events to prevent unnecessary loadings
                    f7.infiniteScroll.destroy(
                      `${self.infiniteId} .infinite-scroll-content`
                    )
                    // Remove preloader
                    self
                      .$$(`${self.infiniteId} .infinite-scroll-preloader`)
                      .remove()
                  }
                  Array.isArray(res.data.result) &&
                    res.data.result.length &&
                    res.data.result.forEach((item) => {
                      self.vlData.items.push(item)
                    })
                }
              })
              .catch((err) => {
                console.log(err)
                self.allowInfinite = true
              })
          }
        })
    })
  },
  beforeDestroy() {
    console.log('销毁了songcatalog组件', this.id)
    //销毁总线监听
    // this.$bus.$off("delInMultiplechoice");
  },
}
</script>
<style lang="scss" scoped>
@import '@/assets/scss/theme.scss';
.light .popover {
  $spanColor: #212121;
  /deep/ a {
    color: $spanColor;
  }
}
.dark .popover {
  $spanColor: #ffffff;
  /deep/ a {
    color: $spanColor;
  }
}
.light .card {
  $backgroundColor: #d9e7e7;
  /deep/ .card-content {
    color: $backgroundColor;
  }
}
.dark .card {
  $backgroundColor: #212121;
  /deep/ .card-content {
    color: $backgroundColor;
  }
}
.buttonBar_box {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 7vh;
}
.songcatalog_box {
  .itemTitle {
    display: flex;
    align-items: center;
    .index_box {
      width: 0.3rem;
      flex-shrink: 0;
      .svg-icon {
        width: 0.2rem;
        height: 0.2rem;
      }
    }
  }
  .itemFooter {
    display: flex;
    align-items: center;
    margin-left: 0.28rem;
    .svg-icon {
      width: 0.2rem;
      height: 0.2rem;
    }
  }
  .list {
    margin: 0;
    overflow-y: scroll;
    height: 60vh;
  }
}
</style>
